<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>时间戳转换</title>
</head>
<body>
    

<script>
    function timestampTransform(timestamp, str = 'Y-m-d H:i:s'){
        if(String(timestamp).length > 13) timestamp = Math.round(timestamp / Math.pow(10, String(timestamp).length - 13));
        if(String(timestamp).length < 13) timestamp = Math.round(timestamp * Math.pow(10, 13 - String(timestamp).length));
        let date = new Date(timestamp || Date.now()),
            arr = str.split(''),
            newArr = [],
            fill = (num) => num > 9 ? num : '0' + num;
        arr.map(item => {
            switch(item){
                case 'Y':
                    newArr.push(date.getFullYear());
                    break;
                case 'y':
                    newArr.push(date.getYear());
                    break;
                case 'm':
                    newArr.push(fill(date.getMonth() + 1));
                    break;
                case 'd':
                    newArr.push(fill(date.getDate()));
                    break;
                case 'H':
                    newArr.push(fill(date.getHours()));
                    break;
                case 'i':
                    newArr.push(fill(date.getMinutes()));
                    break;
                case 's':
                    newArr.push(fill(date.getSeconds()));
                    break;
                default:
                    newArr.push(item);
                    break;
            }
        });
        return newArr.join('');
    }
</script>
<script>
    let time = timestampTransform();
    console.log('time:', time);
</script>
</body>
</html>